import { Component, ViewChild, ElementRef, NgZone, Input, Output, EventEmitter } from '@angular/core';
import { SessionService } from '../../services/session-service';
import * as $ from 'jquery';
import { DOMAIN } from '../../app.config';
// import '../../../../vender/plupload.min.js';
declare var plupload: any;

export interface PhotoResponse {
    path?: string;
    id?: number;
    faceId?: number;
}

@Component({
    selector: 'photo-uploader',
    templateUrl: 'photo-upload.component.html',
    styleUrls: ['./photo-upload.component.scss'],
    providers: [SessionService]
})
export class PhotoUploadComponent {

    photoResponses: PhotoResponse[] = [];

    private _photoSrc: any[];
    private _percent: number;
    @Input()
    instanceId: string;
    @Input()
    RemotePath: string;
    @Input()
    paramId: number;
    @Output()
    UploadedCb: EventEmitter<any> = new EventEmitter<any>(true);
    @Output()
    ErrorCb: EventEmitter<any> = new EventEmitter<any>(true);
    @Output()
    PercentCb: EventEmitter<any> = new EventEmitter<any>(true);
    @Output()
    PhotoSrcChange: EventEmitter<any> = new EventEmitter<any>(true);
    @Output()
    PercentChange: EventEmitter<any> = new EventEmitter<any>(true);

    @Input()
    set PhotoSrc(val) {
        this._photoSrc = val || [];
        this.PhotoSrcChange.emit(val);
    }
    get PhotoSrc() {
        return this._photoSrc;
    }

    @Input()
    set Percent(val) {
        this._percent = val || 0;
        this.PercentChange.emit(val);
    }

    get Percent() {
        return this._percent;
    }

    getUrl = (path: string): string => DOMAIN + path;

    constructor(
        private _ngZone: NgZone,
        private _dom: ElementRef,
        private _sessionService: SessionService
    ) {
        // console.log('%c photo uploader init...', 'color: blue;')
    }
    public deleteImg(index) {
        this.PhotoSrc.splice(index, 1);
    }
    ngAfterViewInit() {
        let dom = $(this._dom.nativeElement).find('#upload-btn')[0];
        console.log(dom);
        let uploader = new plupload.Uploader({
            headers: {
                'Authorization': `Bearer ${this._sessionService.getToken()}`
            },
            multi_selection: false,
            runtimes: 'html5,html4',
            browse_button: this.instanceId,
            max_file_size: '10mb',
            // container: 'file-btn-container',
            // url: `${'DOMAIN'}/v1/api/photo/${this.RemotePath}`,
            url: `${DOMAIN}/v1/api/photo/${this.RemotePath}`,
            filters: [{
                title: "Image files",
                extensions: "jpg,gif,png,jpeg"
            }],
            init: {
                BeforeUpload: (up, files) => {
                    // this._showLoading(true);
                    up.settings.file_data_name = 'imageFiles';
                    // up.settings.url = "";
                },
                PostInit: function() {
                    console.log('init');
                },

                FilesAdded: function(up, files) {
                    up.start();
                },

                UploadProgress: (up, file) => {
                    console.log(file);
                    this._ngZone.run(() => {
                        this.Percent = file.percent;
                        this.PercentCb.emit({ percent: file.percent });
                    })
                    // $(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                },
                FileUploaded: (up, file, info) => {
                    let ret = JSON.parse(info.response);
                    this._ngZone.run(() => {
                        let res: PhotoResponse = {
                            path: ret.path,
                            id: ret.id,
                            faceId: ret.faceId
                        }
                        this.PhotoSrc.push(res);
                        this.UploadedCb.emit({ id: ret.Id, category: this.RemotePath });
                        // this._showLoading(false);
                    });
                },
                UploadComplete: (up, file, info) => {
                    this._ngZone.run(() => {
                        this.Percent = 0;
                        // this._showLoading(false);
                    });
                },
                Error: (up, err) => {
                    this._ngZone.run(() => {
                        let errResp = JSON.parse(err.response);
                        this.ErrorCb.emit(errResp);
                        // this._showLoading(false);
                    });
                }
            }
        });

        uploader.init();
    }
}